import { http, HttpResponse } from 'msw';

let mockUserData = {
    userId: 1,
    username: '测试员',
    email: "test@example.com",
    nickname: '测试员',
    bio:"只要不出bug一切都好QAQ",
    gender:'F',
    birthday: '2000-01-01',
    studentId:20220101001,
    department: "计算机学院",
    major: "软件工程",
    grade: "2023级",
    points: 100,
    role: 0,
    status:1,
    isVerified: true,
}

// mock 帖子数据
let mockForumPosts = [
  { id: 1, title: 'Vue3实用技巧', author: '小明', likes: 12, time: '2025-06-20', category: '编程', content: '分享一些Vue3开发中的实用技巧...' },
  { id: 2, title: '高数期末复习资料', author: '小红', likes: 30, time: '2025-06-18', category: '高数', content: '整理了高数期末复习的重点和资料...' },
  { id: 3, title: '考研经验贴', author: '学长', likes: 25, time: '2025-06-15', category: '考研', content: '考研备考心得与建议...' },
  { id: 4, title: '大学生活分享', author: '小李', likes: 8, time: '2025-06-10', category: '生活', content: '聊聊大学生活的点滴...' },
  { id: 5, title: '算法刷题打卡', author: '小王', likes: 20, time: '2025-06-22', category: '编程', content: '每日一道算法题，欢迎参与讨论...' },
]

// 帖子管理相关 mock
let mockPosts = [
  { id: 1, authorId: 1, title: 'Vue3实用技巧', content: '内容1', status: 0, commentCount: 2, likeCount: 12, createTime: '2025-06-20', updateTime: '2025-06-21' },
  { id: 2, authorId: 1, title: '高数期末复习资料', content: '内容2', status: 0, commentCount: 1, likeCount: 30, createTime: '2025-06-18', updateTime: '2025-06-19' },
  { id: 3, authorId: 1, title: '考研经验贴', content: '内容3', status: 2, commentCount: 3, likeCount: 25, createTime: '2025-06-15', updateTime: '2025-06-16' },
  { id: 4, authorId: 2, title: '算法打卡', content: '内容4', status: 0, commentCount: 0, likeCount: 18, createTime: '2025-06-10', updateTime: '2025-06-11' },
  { id: 5, authorId: 2, title: '大学生活', content: '内容5', status: 0, commentCount: 2, likeCount: 10, createTime: '2025-06-22', updateTime: '2025-06-22' },
  { id: 6, authorId: 3, title: '考研资料', content: '内容6', status: 0, commentCount: 1, likeCount: 8, createTime: '2025-06-17', updateTime: '2025-06-18' },
  { id: 7, authorId: 3, title: '软件工程导论', content: '内容7', status: 0, commentCount: 0, likeCount: 15, createTime: '2025-06-12', updateTime: '2025-06-13' },
  { id: 8, authorId: 2, title: '前端面试题', content: '内容8', status: 0, commentCount: 4, likeCount: 22, createTime: '2025-06-23', updateTime: '2025-06-23' },
  { id: 9, authorId: 4, title: '生活感悟', content: '内容9', status: 0, commentCount: 2, likeCount: 5, createTime: '2025-06-24', updateTime: '2025-06-24' },
]

// 评论相关mock
let mockComments = [
  { id: 1, postId: 1, userId: 1, content: '很有用，谢谢分享！', createTime: '2025-06-20', status: 0, likeCount: 2 },
  { id: 2, postId: 1, userId: 2, content: '有问题可以私信我', createTime: '2025-06-21', status: 0, likeCount: 1 },
  { id: 3, postId: 2, userId: 1, content: '资料很全，赞！', createTime: '2025-06-18', status: 0, likeCount: 3 },
]

export const handlers = [
  // 注册接口 mock
  http.post('/users/register', async ({ request }) => {
    const { email, password, code } = await request.json() as { email: string; password: string; code: string };
    // 简单校验
    if (!email || !password || !code) {
      return HttpResponse.json({ code: 1, message: '缺少必要参数', data: {} }, { status: 400 });
    }
    // 假设验证码为 123456
    if (code !== '123456') {
      return HttpResponse.json({ code: 2, message: '验证码错误', data: {} }, { status: 400 });
    }
    // 注册成功
    return HttpResponse.json({ code: 0, message: '注册成功', data: {} });
  }),

  // 发送验证码接口 mock
  http.post('/users/code', async ({ request }) => {
    const { email } = await request.json() as { email: string };
    if (!email) {
      return HttpResponse.json({ code: 1, message: '邮箱不能为空', data: {} }, { status: 400 });
    }
    // 假设发送成功
    return HttpResponse.json({ code: 0, message: '验证码已发送', data: {} });
  }),

    // 密码登录接口 mock
  http.post('/users/loginByPassword', async ({ request }) => {
    const { email, password } = await request.json() as { email: string; password: string };
    if (email === 'test@example.com' && password === '123456') {
      return HttpResponse.json({
        code: 200,
        data: {
          id:mockUserData.userId,
          nickname: mockUserData.nickname,
          gender: mockUserData.gender,
          personalIntroduce: mockUserData.bio,
          birthday: mockUserData.birthday,
        },
        message: '登录成功'
      });
    } else {
      return HttpResponse.json({ code: 401, message: '账号或密码错误' }, { status: 401 });
    }
  }),

  // 验证码登录接口 mock
  http.post('/users/loginByCode', async ({ request }) => {
    const { email, code } = await request.json() as { email: string; code: string };
    if (email === 'test@example.com' && code === '123456') {
      return HttpResponse.json({
        code: 200,
        data: {
          nickname: '测试员',
          gender: 'F',
          personalIntroduce: '只要不出bug一切都好QAQ',
          birthday: '2000-01-01',
          is_Login: 'Y',
          email: 'test@example.com'
        },
        message: '登录成功'
      });
    } else {
      return HttpResponse.json({ code: 401, message: '验证码错误' }, { status: 401 });
    }
  }),

  // 修改用户基本信息 mock
  http.post('/users/updateCommonData', async ({ request }) => {
    const body = await request.json() as { nickname: string; gender: string; birthday: string };
    // 简单校验
    if (!body.nickname || !body.gender || !body.birthday) {
      return HttpResponse.json({ code: 400, message: '缺少必要信息' }, { status: 400 });
    }
    return HttpResponse.json({ code: 200, message: '信息更新成功', data: { ...body } });
  }),

  // 修改密码接口 mock
  http.post('/users/updatePassword', async ({ request }) => {
    const { email, code, newPassword } = await request.json() as { email: string; code: string; newPassword: string };
    if (!email || !code || !newPassword) {
      return HttpResponse.json({ code: 400, message: '缺少参数' }, { status: 400 });
    }
    if (code !== '123456') {
      return HttpResponse.json({ code: 401, message: '验证码错误' }, { status: 401 });
    }
    return HttpResponse.json({ code: 200, message: '密码修改成功' });
  }),

  // 重置密码接口 mock
  http.post('/users/resetPassword', async ({ request }) => {
    const { email, code } = await request.json() as { email: string; code: string };
    if (!email || !code) {
      return HttpResponse.json({ code: 400, message: '缺少参数' }, { status: 400 });
    }
    if (code !== '123456') {
      return HttpResponse.json({ code: 401, message: '验证码错误' }, { status: 401 });
    }
    return HttpResponse.json({ code: 200, message: '密码重置成功' });
  }),










  //帖子相关的mock测试
  //全部帖子列表获取接口 mock
  http.get('/api/forum/posts', () => {
    return HttpResponse.json({ success: true, posts: mockForumPosts })
  }),

  // 创建帖子接口 mock
  http.post('/posts', async ({ request }) => {
    const body = await request.json() as { 
      authorId: number; 
      title: string; 
      content: string; 
      categoryId?: number;
      authorNickname?: string;
      authorAvatar?: string;
    };
    if (!body || !body.title || !body.content || !body.authorId) {
      return HttpResponse.json({ code: 400, message: '缺少必要参数' }, { status: 400 });
    }
    
    // 创建新帖子
    const newPost = {
      id: mockPosts.length + 1,
      authorId: body.authorId,
      title: body.title,
      content: body.content,
      categoryId: body.categoryId || 1,
      authorNickname: body.authorNickname || '匿名用户',
      authorAvatar: body.authorAvatar || '',
      status: 0,
      commentCount: 0,
      likeCount: 0,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    };
    
    mockPosts.push(newPost);
    
    return HttpResponse.json({ 
      code: 0, 
      message: '创建成功', 
      data: newPost 
    });
  }),

  // 获取作者帖子（分页，返回数组，字段全量，结构与响应示例一致）
  http.get('/posts/author/:authorId', ({ params, request }) => {
    const { authorId } = params
    const url = new URL(request.url)
    const page = Number(url.searchParams.get('page') || 1)
    const size = Number(url.searchParams.get('size') || 5)
    const list = mockPosts.filter(p => String(p.authorId) === String(authorId) && p.status !== 1)
    const paged = list.slice((page - 1) * size, page * size)
    // 保证每个字段都存在
    const normalized = paged.map(p => ({
      id: p.id ?? 0,
      authorId: p.authorId ?? 0,
      title: p.title ?? '',
      content: p.content ?? '',
      status: p.status ?? 0,
      commentCount: p.commentCount ?? 0,
      likeCount: p.likeCount ?? 0,
      createTime: p.createTime ?? '',
      updateTime: p.updateTime ?? ''
    }))
    return HttpResponse.json(normalized)
  }),



  // 删除帖子
  http.delete('/posts/:id', ({ params }) => {
    const { id } = params
    const idx = mockPosts.findIndex(p => String(p.id) === String(id))
    if (idx !== -1) mockPosts[idx].status = 1
    return HttpResponse.json({ code: 0, message: '删除成功' })
  }),

  // 更新帖子（隐藏/取消隐藏）
  http.put('/posts', async ({ request }) => {
    const body = await request.json() as {id: number, title?: string, content?: string, status?: number}
    if (!body) {
      return HttpResponse.json({ code: 1, message: '请求体不能为空' }, { status: 400 })
    }
    const idx = mockPosts.findIndex(p => p.id === body.id)
    if (idx !== -1) {
      mockPosts[idx] = { ...mockPosts[idx], ...body, updateTime: new Date().toISOString() }
      return HttpResponse.json({ code: 0, message: '更新成功' })
    }
    return HttpResponse.json({ code: 1, message: '未找到帖子' }, { status: 404 })
  }),

  // 获取单个帖子详情
  http.get('/posts/:id', ({ params }) => {
    const { id } = params
    const post = mockPosts.find(p => String(p.id) === String(id))
    if (post) {
      // 保证每个字段都存在
      return HttpResponse.json({
        id: post.id ?? 0,
        authorId: post.authorId ?? 0,
        title: post.title ?? '',
        content: post.content ?? '',
        status: post.status ?? 0,
        commentCount: post.commentCount ?? 0,
        likeCount: post.likeCount ?? 0,
        createTime: post.createTime ?? '',
        updateTime: post.updateTime ?? ''
      })
    } else {
      return HttpResponse.json({
        id: 0,
        authorId: 0,
        title: '',
        content: '',
        status: 0,
        commentCount: 0,
        likeCount: 0,
        createTime: '',
        updateTime: ''
      }, { status: 404 })
    }
  }),

  // 添加评论
  http.post('/comments', async ({ request }) => {
    const body = await request.json() as { postId: number; userId: number; content: string }
    if (!body) {
      return HttpResponse.json({ success: false, message: '请求体不能为空' }, { status: 400 })
    }
    const newComment = {
      id: mockComments.length + 1,
      postId: body.postId,
      userId: body.userId,
      content: body.content,
      createTime: new Date().toISOString(),
      status: 0,
      likeCount: 0
    }
    mockComments.push(newComment)
    return HttpResponse.json({ success: true, id: newComment.id })
  }),

  // 删除评论
  http.delete('/comments/:id', ({ params }) => {
    const { id } = params
    const idx = mockComments.findIndex(c => String(c.id) === String(id))
    if (idx !== -1) mockComments.splice(idx, 1)
    return HttpResponse.json({ success: true })
  }),

  // 根据帖子ID获取评论列表
  http.get('/comments/post/:postId', ({ params }) => {
    const { postId } = params
    const list = mockComments.filter(c => String(c.postId) === String(postId))
    return HttpResponse.json(list)
  }),

  // 点赞评论
  http.post('/comments/:id/like', ({ params }) => {
    const { id } = params
    const comment = mockComments.find(c => String(c.id) === String(id))
    if (comment) comment.likeCount++
    return HttpResponse.json({ success: true })
  }),

  // 获取单条评论详情
  http.get('/comments/:id', ({ params }) => {
    const { id } = params
    const comment = mockComments.find(c => String(c.id) === String(id))
    if (comment) return HttpResponse.json(comment)
    return HttpResponse.json({}, { status: 404 })
  }),

  // 帖子搜索接口 mock 支持 keyword 参数
  http.get('/posts', ({ request }) => {
    const url = new URL(request.url);
    const keyword = url.searchParams.get('keyword') || '';
    let list = mockForumPosts; // 修改为 mockForumPosts
    if (keyword) {
      list = list.filter(p => p.title.includes(keyword) || p.content.includes(keyword));
    }
    console.log('mockForumPosts:', list, 'keyword:', keyword);
    return HttpResponse.json({ list, total: list.length });
  }),
];